// 被订阅的事件会保存在cache中，当emit时找到对应的事件名，执行里面的callback函数
class EventBus {
  constructor() {
    this.cache = {};
  }
  //   订阅
  on(event, fn) {
    if (typeof fn !== "function") {
      throw new Error("必须是函数");
    }
    if (!this.cache[event]) {
      this.cache[event] = [fn];
    } else {
      this.cache[event].push(fn);
    }
  }

  // 发布
  emit(event, ...args) {
    // 如果有这个事件
    if (this.cache[event]) {
      this.cache[event].forEach((fn) => {
        fn(...args);
      });
    }
  }

  //   取消订阅
  off(event, fn) {
    if (this.cache[event]) {
      this.cache[event] = this.cache[event].filter((item) => item != fn);
    }
  }
}

const ee = new EventBus();
function sayHi(name) {
  console.log("hi1", name);
}

function sayHi2(name) {
  console.log("hi2", name);
}

ee.on("sayHi", sayHi);
ee.on("sayHi", sayHi2);

ee.emit("sayHi", "bob", 1);
